package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.RecordDuplicateException;

import service.cart.CartService;
import service.cart.CartServiceFactory;
import servlet.ServletInitParams;
import entities.Cart;



/**
 * Servlet implementation class HonorRollServlet
 */
public class AddCartServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddCartServlet() 
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		HttpSession session = request.getSession();
		
		Cart cart = createCart(request);
		String addr = null;
		
		// Get the factory to create services. This is obtained from the web.xml configuration file
		// from parameter ServiceFactoryType
		CartServiceFactory factory = CartServiceFactory.getFactory(ServletInitParams.getServiceFactoryType(this));
		// Get an instance of the student service, as given by the factory
		CartService service = factory.getInstance();

		try {
			service.addCart(cart);
			session.setAttribute("cart", cart);
			addr = "html/shopcart.jsp";
		} catch (RecordDuplicateException e) {
			session.setAttribute("cart", cart);
			addr = "html/shopcart.jsp";
		}
			
	
		// forward the request to the page previously determined
		RequestDispatcher dispatcher = request.getRequestDispatcher(addr);
		dispatcher.forward(request, response);
	}

	private Cart createCart(HttpServletRequest request) {
		String title = request.getParameter("title");
		String img = request.getParameter("img");
		String action = request.getParameter("action");
		String tempQty = request.getParameter("qty");
		String price = request.getParameter("price");
		
		
		int qty = Integer.valueOf(tempQty);
		Cart cart = null;
		cart = Cart.newInstance(title, img, qty, price, action);
		
		return cart;
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
